package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private TimeLineService timeLineService;
    @Autowired
    private IdWorker idWorker;


    @Override
    public void  publish(Movement movement) {
        try {
            //设置Pid用于推荐系统，根据表sequence里的字段进行自增
            movement.setPid(idWorker.getNextId("movement"));
            //创建时间
            movement.setCreated(System.currentTimeMillis());
            //保存动态
            mongoTemplate.save(movement);
            //查询当前用户的所有好友信息
//        Query query = new Query();
//        query.addCriteria(Criteria.where("userId").is(movement.getUserId()));
//        List<Friend> friends = mongoTemplate.find(query, Friend.class);
//        //对好友信息进行遍历封装时间线动态时间线对象进行动态保存
//        for (Friend friend : friends) {
//            MovementTimeLine movementTimeLine = new MovementTimeLine();
//            movementTimeLine.setMovementId(movement.getId());
//            movementTimeLine.setCreated(System.currentTimeMillis());
//            movementTimeLine.setUserId(movement.getUserId());
//            movementTimeLine.setFriendId(friend.getFriendId());
//            mongoTemplate.save(movementTimeLine);
//        }
            timeLineService.saveTimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page -1 ) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0l,movements);
    }

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize, Integer status) {
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(status);
        Query query = Query.query(criteria)
                .with(PageRequest.of(page-1, pagesize))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0l,movements);
    }

    @Override
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
// TODO: 2021/9/20  
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        List<Long> friendId = CollUtil.getFieldValues(friends, "friendId",Long.class);
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("userId").in(friendId))
                .with(Sort.by(Sort.Direction.DESC, "created"));
        return mongoTemplate.find(query1, Movement.class);
    }

    @Override
    public List<Movement> randomMovements(Integer pagesize) {
        //构建聚焦、统计参数
        TypedAggregation<Movement> aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(pagesize));
        //初始化统计对象
        AggregationResults<Movement> aggregationResults = mongoTemplate.aggregate(aggregation, Movement.class);

        return aggregationResults.getMappedResults();
    }

    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        Query query = new Query(Criteria.where("pid").in(pids));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return movementList;
    }

    @Override
    public Movement findByMovementId(String movementId) {
        return mongoTemplate.findById(movementId, Movement.class);
    }
}
